package cn.ulyer.core.secure;

import cn.ulyer.common.transcode.secret.KeyProvider;
import cn.ulyer.common.utils.OauthUtil;
import cn.ulyer.core.domain.ClientInfo;
import cn.ulyer.core.service.ClientInfoService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.NativeWebRequest;

@Component
public class ClientSecretProvider implements KeyProvider {

    final String CLIENT_KEY = "client_id";

    @Autowired
    private ClientInfoService clientInfoService;

    /**
     * 从当前的认证token 用户中读取
     * @param nativeWebRequest
     * @param parameter
     * @return
     */
    @Override
    public Object key(NativeWebRequest nativeWebRequest, Object parameter) {
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(parameter);
        String clientId = null;
        if(jsonObject!=null){
            clientId = jsonObject.getString(CLIENT_KEY);
        }
        if(StringUtils.isBlank(clientId)){
            clientId = OauthUtil.getClientId();
        }
        ClientInfo clientInfo = clientInfoService.getById(clientId);
        return clientInfo==null?null:clientInfo.getClientSecret();
    }
}
